import sys
sys.path.append("..")

import utils.raster as raster

import numpy as np
import datetime
import os

def days_after_last_rain(precp_data_path,start_date,end_date,thrd = 1):
	 s_date = datetime.datetime.strptime(start_date,"%Y%m%d")
	 e_date = datetime.datetime.strptime(end_date,"%Y%m%d")

	 days = (e_date - s_date).days

	 previous_dlr = None

	 for day_delta in range(days + 1):
	 	current_day = s_date + datetime.timedelta(days = day_delta)
	 	current_file = os.path.join(precp_data_path,"tp_%s.tif"%(datetime.datetime.strftime(current_day,"%Y%j")))


	 	if not os.path.exists(current_file):
	 		raise IOError("File or directory does not exists")

	 	(current_info, current_rain) = raster.open(current_file)

	 	# 1: rained
	 	is_rain = current_rain >= thrd

	 	if day_delta == 0:
	 		days_last_rain = (~is_rain).astype(np.int8)
	 	else:
	 		days_last_rain = (previous_dlr + 1) * (~is_rain)

	 	dlr_path = os.path.join(precp_data_path,"dlr","dlr_%s.tif"%(datetime.datetime.strftime(current_day,"%Y%j")))
	 	raster.save(dlr_path,days_last_rain,255,current_info[1],current_info[2])

	 	previous_dlr = days_last_rain

if __name__ == '__main__':
	days_after_last_rain("/mnt/fire/Extract/tp","20121201","20171231",thrd = 1)




